var http = require("http");
var url = require("url");
var qs = require('querystring');
var serchs = require('./serch');
var async = require('async');
function start(route) {
    var app = http.createServer(onRequest);
    var io = require('socket.io').listen(app);
   
    async function onRequest(request, response) {
        var json =await new Promise((reslove,reject) => {
            if (request.method.toUpperCase() == 'POST') {
                var postData = "";
                request.addListener("data", function (data) {
                    postData += data;
                });
                /**
                 * 这个是如果数据读取完毕就会执行的监听方法
                 */
                request.addListener("end",async function () {
                    var query = eval("("+postData+")");
                    var id = await command.control(query);
                  
                    // var id =await route(query, response);
                    var res = await serchs.find(id);
                    reslove(res)
                });
            } else if (request.method.toUpperCase() == 'GET') {
                /**
                 * 也可使用var query=qs.parse(url.parse(req.url).query);
                 * 区别就是url.parse的arguments[1]为true：
                 * ...也能达到‘querystring库’的解析效果，而且不使用querystring
                 */
                var pathname = url
                    .parse(request.url, true)
                    .query;
                route(pathname);
            } else {
                //head put delete options etc.
            }
           
        }) 
      
        response.writeHead(200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Request-Method': '*',
            "Content-Type": "text/html;charset=utf-8"
        });
        // response.write(json);
        response.end(JSON.stringify(json[0]));
    }

    app.listen(8000);
    console.log("Server has started.8000");
    var q = async.queue(async function(task, callback) {
        var id = await route(task.word,task.device);
        var res = await serchs.find(id);
        //向指定客户端发送消息
        task.socket.emit('goback',res[0])
        callback();
    }, 2);

    q.drain = function() {
        console.log('all items have been processed');
    };

    io.sockets.on('connection',function(socket){
        socket.on('capture', function(query){
            query[2].forEach(async function(equip){
                q.push({word:query[0],pages:query[1],device: equip,socket:socket});    
            })
          });
        socket.on('disconnect',function(){
            console.log('客户端断开连接');
        }); 
    })
    

}

exports.start = start;